﻿using Agile.Infra.Core.Agile.Extensions;
using Agile.Infra.Core.Exceptions;
using Agile.Infra.IdGenerator.Yitter;
using Microsoft.Extensions.Logging;

namespace Agile.Shared.WebApi.Middlewares
{
    public class ExceptionsMiddleware
    {
        private readonly RequestDelegate _next;
        public ExceptionsMiddleware(RequestDelegate next)
        {
            _next = next;
        }

        public async Task Invoke(HttpContext httpContext)
        {
            async Task WriteErrorResponseAsync(ResponseStatus status, string errorMsg)
            {
                var messageModel = new
                {
                    success = false,
                    status = status,
                    message = errorMsg
                };
                await httpContext.WriteRespnseAsync(messageModel.ToJsonString(), "text/json;charset=utf-8;");
            }
            try
            {
                await _next.Invoke(httpContext);
            }
            catch (BusinessException ex)
            {
                await WriteErrorResponseAsync(ResponseStatus.Code200, ex.Message);
            }
            catch (Exception ex)
            {
                var logID = IdGenerater.GetNextId();
                httpContext.RequestServices.GetService<ILogger<ExceptionsMiddleware>>()?.LogError(ex, $"{logID} {ex.Message}");
                await WriteErrorResponseAsync(ResponseStatus.Code500, $"服务器未处理的异常：错误代码 {logID}");
            }
        }
    }
}
